<template>
  <div>
    <el-select v-model="state.questionType" placeholder="选择题目类型" size="large" class="margin10px" clearable>
      <el-option label="单选题" value="1" />
      <el-option label="多选题" value="2" />
      <el-option label="判断题" value="3" />
      <el-option label="简答题" value="4" />
    </el-select>

    <el-select v-model="state.questionBank" placeholder="选择题库" size="large" class="margin10px" clearable>
      <el-option v-for="bank in state.questionBanks" :key="bank.bankId" :label="bank.bankName" :value="bank.bankName" />
    </el-select>

    <el-input v-model="state.questionContent" placeholder="题目内容" @blur="handleInput" @keyup.enter="handleInput"
      size="large" class="margin10px" />
    <br>

    <el-button type="primary" class="margin10px" @click="addDialogVisible = true" size="large"
      style="width: 90px;">+&nbsp;添加</el-button>
    <br>
    <el-select class="margin10px" v-model="selectValue" clearable :placeholder="selectPlaceholder" size="large"
      v-if="state.selectedRows.length > '0'" @change="handleSelectChange">
      <el-option label="删除" value="delete" />
      <el-option label="加入题库" value="addToBank" />
      <el-option label="从题库中移除" value="removeFromBank" />
    </el-select>

    <el-table :data="formattedQuestionData" border style="width: 100%" header-background="#f2f3f4"
      @selection-change="handleSelectionChange" tooltip-effect="dark">
      <el-table-column type="selection" width="55" />
      <el-table-column property="quType" label="题目类型" />
      <el-table-column label="题目内容" width="350">
        <template v-slot="scope">
          <span class="updateSpan" @click="updateQuestion(scope.row)">{{ scope.row.quContent }}</span>
        </template>
      </el-table-column>


      <el-table-column property="level" label="难度" />
      <el-table-column property="quBankName" label="所属题库" />
      <el-table-column property="createPerson" label="创建人" />
      <el-table-column property="createTime" label="创建时间" width="200" />
    </el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="state.pageNum" v-model:page-size="state.pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="state.total" @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 添加题目对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加题目" width="60%" center>
      <el-card>
        <el-form :model="addForm" label-width="120px">
          <el-form-item label="题目类型" size="large">
            <el-select v-model="addForm.questionType" placeholder="请选择" style="width: 240px;">
              <el-option label="单选题" value="1" />
              <el-option label="多选题" value="2" />
              <el-option label="判断题" value="3" />
              <el-option label="简答题" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" size="large">
            <el-select v-model="addForm.questionLevel" placeholder="请选择" style="width: 240px;">
              <el-option label="简单" value="1" />
              <el-option label="中等" value="2" />
              <el-option label="困难" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" size="large">
            <el-select v-model="addForm.questionBank" placeholder="请选择" multiple style="width: 240px;">
              <el-option v-for="bank in state.questionBanks" :key="bank.bankId" :label="bank.bankName"
                :value="bank.bankId" />
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容">
            <el-input type="textarea" v-model="addForm.questionContent" />
          </el-form-item>
          <el-form-item label="题目图片">
            <el-upload list-type="picture" v-model="addForm.images">
              <el-button slot="trigger" type="primary">选取图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <div style="font-size: 14px; color:#7f7f7f;">只能上传jpg/png文件，且不超过10MB</div>
          </el-form-item>
          <el-form-item label="整题解析">
            <el-input type="textarea" v-model="addForm.analysis" />
          </el-form-item>

          <div v-if="addForm.questionType != 4">
            <el-button type="primary" @click="addOption1" size="large">添加选项</el-button>
            <el-table :data="addForm.options" style="width: 100%; margin-top: 20px;">
              <el-table-column label="是否答案" width="100">
                <template v-slot="scope">
                  <el-checkbox v-model="scope.row.isTrue">答案</el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="答案图片" width="150">
                <template v-slot="scope">
                  <el-upload list-type="picture" v-model="scope.row.images">
                    <el-button slot="trigger" type="primary">点击上传</el-button>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="答案内容">
                <template v-slot="scope">
                  <el-input type="textarea" v-model="scope.row.answer" placeholder="答案内容" />
                </template>
              </el-table-column>
              <el-table-column label="答案解析">
                <template v-slot="scope">
                  <el-input type="textarea" v-model="scope.row.analysis" placeholder="答案解析" />
                </template>
              </el-table-column>

              <el-table-column label="操作" width="100">
                <template v-slot="scope">
                  <el-button type="danger" :icon="Delete" circle size="large" @click="removeOption1(scope.$index)" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </el-card>
      <br>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="addDialogVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="submitAddForm" size="large">提交</el-button>
      </div>
    </el-dialog>


    <!-- 更新试题对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑题目" width="60%" center>
      <el-card>
        <el-form :model="editForm" label-width="120px">
          <el-form-item label="题目类型" size="large">
            <el-select v-model="editForm.questionType" placeholder="请选择" style="width: 240px;">
              <el-option label="单选题" value="1" />
              <el-option label="多选题" value="2" />
              <el-option label="判断题" value="3" />
              <el-option label="简答题" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" size="large">
            <el-select v-model="editForm.questionLevel" placeholder="请选择" style="width: 240px;">
              <el-option label="简单" value="1" />
              <el-option label="中等" value="2" />
              <el-option label="困难" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" size="large">
            <el-select v-model="editForm.questionBank" placeholder="请选择" multiple style="width: 240px;">
              <el-option v-for="bank in state.questionBanks" :key="bank.bankId" :label="bank.bankName"
                :value="bank.bankId" />
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容">
            <el-input type="textarea" v-model="editForm.questionContent" />
          </el-form-item>
          <el-form-item label="题目图片">
            <el-upload list-type="picture" v-model="editForm.images">
              <el-button slot="trigger" type="primary">选取图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <div style="font-size: 14px; color:#7f7f7f;">只能上传jpg/png文件，且不超过10MB</div>
          </el-form-item>
          <el-form-item label="整题解析">
            <el-input type="textarea" v-model="editForm.analysis" />
          </el-form-item>
          <div v-if="editForm.questionType != 4">
            <el-button type="primary" @click="addOption2" size="large">添加选项</el-button>
            <el-table :data="editForm.answer" style="width: 100%; margin-top: 20px;">
              <el-table-column label="是否答案" width="100">
                <template v-slot="scope">
                  <el-checkbox v-model="scope.row.isTrue">答案</el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="答案图片" width="150">
                <template v-slot="scope">
                  <el-upload list-type="picture" v-model="scope.row.images">
                    <el-button slot="trigger" type="primary">点击上传</el-button>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="答案内容">
                <template v-slot="scope">
                  <el-input type="textarea" v-model="scope.row.answer" placeholder="答案内容" />
                </template>
              </el-table-column>
              <el-table-column label="答案解析">
                <template v-slot="scope">
                  <el-input type="textarea" v-model="scope.row.analysis" placeholder="答案解析" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template v-slot="scope">
                  <el-button type="danger" :icon="Delete" circle size="large" @click="removeOption2(scope.$index)" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </el-card>
      <br>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="editDialogVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="submitEditForm" size="large">确认</el-button>
      </div>
    </el-dialog>
    <!-- 添加题库对话框 -->
    <el-dialog v-model="addToBankDialogVisible" title="加入题库" width="60%">
      <el-card>
        <el-form :model="addToBankForm" label-width="120px">
          <el-form-item label="选择题库" size="large">
            <el-select v-model="addToBankForm.banks" placeholder="请选择" multiple style="width: 240px;">
              <el-option v-for="bank in state.questionBanks" :key="bank.bankId" :label="bank.bankName"
                :value="bank.bankId" />
            </el-select>
          </el-form-item>
        </el-form>
        <br>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addToBankDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddToBank">确认</el-button>
        </div>
      </el-card>
    </el-dialog>
    <!-- 从题库中移除对话框 -->
    <el-dialog v-model="removeFromBankDialogVisible" title="从题库中移除" width="60%">
      <el-card>
        <el-form :model="removeFromBankForm" label-width="120px">
          <el-form-item label="选择题库" size="large">
            <el-select v-model="removeFromBankForm.banks" placeholder="请选择" multiple style="width: 240px;">
              <el-option v-for="bank in state.questionBanks" :key="bank.bankId" :label="bank.bankName"
                :value="bank.bankId" />
            </el-select>
          </el-form-item>
        </el-form>
        <br>
        <div slot="footer" class="dialog-footer">
          <el-button @click="removeFromBankDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemoveFromBank">确认</el-button>
        </div>
      </el-card>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, inject, watch } from 'vue';
import { Delete } from '@element-plus/icons-vue';
import { ElMessage, ElNotification } from 'element-plus';
import {
  getQuestionBank,
  getQuestion,
  removeBankQuestion,
  addBankQuestion,
  deleteQuestion,
  getQuestionById,
  updateQuestions,
  addQuestion
} from '@/api/examControl/QuestionManage'

const selectPlaceholder = ref('');
const selectValue = ref('')
const state = reactive({
  questionData: [],
  questionBanks: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  questionType: '',
  questionBank: '',
  questionContent: '',
  selectedRows: [],
});

const formattedQuestionData = computed(() => {
  return state.questionData.map(question => ({
    ...question,
    quType: question.quType == 1 ? '单选题' : question.quType == 2 ? '多选题' : question.quType == 3 ? '判断题' : '简答题',
    level: question.level == 1 ? '简单' : question.level == 2 ? '中等' : '困难',
  }));
});

watch(() => [state.questionType, state.questionBank], () => {
  getQuestionInfo();
});

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  state.pageSize = val;
  getQuestionInfo();
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  state.pageNum = val;
  getQuestionInfo();
};

async function getQuestionBanks() {
  try {
    let {data }= await getQuestionBank();
    state.questionBanks = data.data;
    console.log(state.questionBanks);
    
  } catch (error) {
    console.error('获取题库列表时出错:', error);
  }
}

async function getQuestionInfo() {
  try {
    let  {data}  = await getQuestion({
        questionType: state.questionType || '',
        questionBank: state.questionBank || '',
        questionContent: state.questionContent || '',
        pageNo: state.pageNum,
        pageSize: state.pageSize,
      });
    state.questionData = data.data.questions;
    state.total = data.data.total;
  } catch (error) {
    console.error('获取题目列表时出错:', error);
  }
}

const handleInput = () => {
  getQuestionInfo();
};

const handleSelectionChange = (selectedRows: any[]) => {
  state.selectedRows = selectedRows;
  console.dir(state.selectedRows);
  addToBankForm.banks = [];
  removeFromBankForm.banks = [];
  selectValue.value = '';
  selectPlaceholder.value = `已选择${selectedRows.length}项`;
};
const handleSelectChange = async (value: string) => {
  if (value == 'delete') {
    await handleDelete();
  } else if (value == 'addToBank') {
    addToBankDialogVisible.value = true;
  } else if (value == 'removeFromBank') {
    // 获取选中题目的题库信息
    const selectedBanks = state.selectedRows.map(row => row.quBankId).flat();
    removeFromBankForm.banks = selectedBanks; // 回显题库信息
    removeFromBankDialogVisible.value = true;
  }
};

const submitRemoveFromBank = async () => {
  try {
    const ids = state.selectedRows.map(row => row.id).join(',');
    const banks = removeFromBankForm.banks.join(',');
    await removeBankQuestion(ids,banks);
    ElMessage.success('试题从题库中移除成功');
    removeFromBankDialogVisible.value = false;
  } catch (error) {
    console.error('从题库中移除失败:', error);
    ElMessage.error('试题从题库中移除失败');
  } finally {
    selectValue.value = '';
    selectPlaceholder.value = '';
    getQuestionInfo();
  }
};


const submitAddToBank = async () => {
  try {
    const ids = state.selectedRows.map(row => row.id).join(',');
    const banks = addToBankForm.banks.join(',');
    await addBankQuestion(ids,banks);
    ElMessage.success('试题加入题库成功');
    addToBankDialogVisible.value = false;
    getQuestionInfo();
  } catch (error) {
    console.error('加入题库失败:', error);
    ElMessage.error('试题加入题库失败');
  } finally {
    addToBankForm.banks = [];
    selectValue.value = '';
    selectPlaceholder.value = '';
    getQuestionInfo();
  }
};

const handleDelete = async () => {
  try {
    const ids = state.selectedRows.map(row => row.id).join(',');
    await deleteQuestion(ids);
    ElMessage.success('试题删除成功');
    getQuestionInfo();
  } catch (error) {
    console.error('删除试题失败:', error);
    ElMessage.error('试题删除失败');
  } finally {
    removeFromBankForm.banks = [];
    selectValue.value = '';
    selectPlaceholder.value = '';
    getQuestionInfo();
  }
};
const addToBankDialogVisible = ref(false);
const removeFromBankDialogVisible = ref(false);
const addToBankForm = reactive({
  banks: [],
});
const removeFromBankForm = reactive({
  banks: [],
});



// 添加题目对话框的状态
const addDialogVisible = ref(false);
// 表单数据
const addForm = reactive({
  questionType: '1',
  questionLevel: '1',
  questionBank: [],
  questionContent: '',
  images: [],
  analysis: '',
  options: [] as Array<{ isTrue: boolean; answer: string; images: any[]; analysis: string }>
});

const editDialogVisible = ref(false);


const editForm = reactive({
  questionType: 0,
  questionId: 0,
  questionLevel: 0,
  questionBank: [],
  questionContent: "",
  analysis: "",
  answer: [],
  createPerson: "admin",
  images: []
})

const updateQuestion = async (row: any) => {
  try {
    const  {data}  = await getQuestionById(row.id);
    editForm.questionId = data.data.questionId;
    editForm.questionType = data.data.questionType.toString();
    editForm.questionLevel = data.data.questionLevel.toString();
    editForm.questionBank = data.data.bankId;
    editForm.questionContent = data.data.questionContent;
    editForm.images = data.data.images || [];
    editForm.analysis = data.data.analysis;
    editForm.answer = data.data.answer.map((answer: any) => ({
      id: answer.id,
      isTrue: answer.isTrue === 'true',
      answer: answer.answer,
      images: answer.images || [],
      analysis: answer.analysis || ''
    }));
    editDialogVisible.value = true; // 打开编辑对话框
  } catch (error) {
    console.error('获取试题信息失败:', error);
  }
};
//点击提交更新
const submitEditForm = async () => {
  try {
    const updateData = {
      ...editForm,
      bankId: editForm.questionBank,
      questionId: editForm.questionId,
      questionType: editForm.questionType,
      questionLevel: editForm.questionLevel,
      questionContent: editForm.questionContent,
      analysis: editForm.analysis,
      answer: editForm.answer,
      createPerson: editForm.createPerson,
      images: editForm.images
    };
    await updateQuestions(updateData);
    ElMessage.success('题目更新成功');
    editDialogVisible.value = false;
    getQuestionInfo();
  } catch (error) {
    console.error('更新题目失败:', error);
    ElMessage.error('题目更新失败');
  }
};
// 添加选项
const addOption1 = () => {
  addForm.options.push({ isTrue: false, answer: '', images: [], analysis: '' });
};
// 移除选项
const removeOption1 = (index: number) => {
  addForm.options.splice(index, 1);
};


// 添加选项
const addOption2 = () => {
  editForm.answer.push({ isTrue: false, answer: '', images: [], analysis: '' });
};
// 移除选项
const removeOption2 = (index: number) => {
  editForm.answer.splice(index, 1);
};

// 提交添加题目表单
const submitAddForm = async () => {
  try {
    let params = {
      questionType: addForm.questionType,
      questionLevel: addForm.questionLevel,
      bankId: addForm.questionBank,
      createPerson: 'admin',
      questionContent: addForm.questionContent,
      images: addForm.images,
      analysis: addForm.analysis,
      answer: addForm.options
    };
    await addQuestion(params);
    ElMessage.success('题目添加成功');
    addDialogVisible.value = false;
    getQuestionInfo();
  } catch (error) {
    console.error('添加题目时出错:', error);
    ElMessage.error('题目添加失败');
  }
};

onMounted(() => {
  getQuestionBanks();
  getQuestionInfo();
});
</script>

<style scoped lang="less">
.updateSpan
{
  text-decoration: none;
  color: #448ef7;
  font-weight: 200;
}

.updateSpan:hover
{
  color: #2980b9;
}

.margin10px
{
  padding: 5px 5px 5px 0;
  display: inline-block;
  margin: 5px 5px 5px 0;
  width: 220px;
}

</style>
